﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Net.Messgae;

public class HomeController : MonoBehaviour
{
    public InputField username;

    public string ServerIp;
    public int ServerPort;

    void Awake()
    {
        Model.Instance().networkManager.SetTcpConnectedEvent(OnConnected,true);
        Model.Instance().networkManager.SetTcpConnectErrorEvent(OnConnectError,true);
        Model.Instance().networkManager.SetTcpDisconnectedEvent(OnDisconnected,true);
        Model.Instance().msgHandler.SetMsgHandler<MessageEnterGameResp>(MessageId.EnterGameResp,OnEnterGameResp,true);
        Waiting.SetTimeout(OnWaitTimeout,true);
    }

    void OnDestroy()
    {
        Model.Instance().networkManager.SetTcpConnectedEvent(OnConnected,false);
        Model.Instance().networkManager.SetTcpConnectErrorEvent(OnConnectError,false);
        Model.Instance().networkManager.SetTcpDisconnectedEvent(OnDisconnected,false);
        Model.Instance().msgHandler.SetMsgHandler<MessageEnterGameResp>(MessageId.EnterGameResp,OnEnterGameResp,false);
        Waiting.SetTimeout(OnWaitTimeout,false);
    }

    void OnWaitTimeout()
    {
        Warnning.Show("连接服务器超时");

        Disconnect();
    }

    void OnConnected()
    {
        Debug.Log("called OnConnected.");

        MessageEnterGameReq req = new MessageEnterGameReq();
        req.OpenId = username.text;
        Model.Instance().msgHandler.SendMessage(MessageId.EnterGameReq,req);
    }

    void OnConnectError()
    {
        // Debug.Log("called OnConnectError.");

        Waiting.SetActive(false);

        Warnning.Show("连接服务器失败");
    }

    void OnDisconnected()
    {
        Waiting.SetActive(false);

        Warnning.Show("与服务器断开连接");
    }

    void Disconnect()
    {
        Model.Instance().networkManager.SetTcpDisconnectedEvent(OnDisconnected,false);

        Model.Instance().networkManager.DisconnectTcp();
    }

    void OnEnterGameResp(uint msgID,MessageEnterGameResp message)
    {
        //Debug.Log("OnEnterGameResp");

        Waiting.SetActive(false);

        if(message.Result != (int)ErrorCode.Successed)
        {
            Warnning.Show("登录错误:" + message.Result,()=>{
                
                Disconnect();
                
            });
            return;
        }

        PlayerInfo player = new PlayerInfo(message.OpenId);

        Model.Instance().playerModel.SetPlayerInfo(player);

        SceneHelper.LoadScene("room");
    }

    public void OnClick()
    {
        if(0 == username.text.Length)
        {
            Warnning.Show("用户名不能为空");
            return;
        }

        Waiting.SetActive(true);

        Model.Instance().networkManager.ConnectTcp(ServerIp,ServerPort);
    }
}
